package com.deyuanyun.pic.settings.controller;

import com.deyuanyun.pic.common.tool.CheckHandler;
import com.deyuanyun.pic.common.tool.ExceplImportCheck;
import com.deyuanyun.pic.common.util.PdfHelper;
import com.deyuanyun.pic.common.util.PdfUtils;
import com.deyuanyun.pic.common.util.RequestUtil;
import com.deyuanyun.pic.common.util.ResponseUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.UploadUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.poi.ReadExcel;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.common.util.web.WebUtil;
import com.deyuanyun.pic.settings.controller.pipe.vo.PipeLocationDTO;
import com.deyuanyun.pic.settings.controller.pipe.vo.PipePositionDTO;
import com.deyuanyun.pic.settings.domain.base.Code;
import com.deyuanyun.pic.settings.domain.pipe.PipeSegment;
import com.deyuanyun.pic.settings.service.base.AttachmentService;
import com.deyuanyun.pic.settings.service.pipe.PipeLineService;
import com.deyuanyun.pic.settings.service.pipe.PipeLocationService;
import com.deyuanyun.pic.settings.service.pipe.PipeSegmentService;
import com.deyuanyun.pic.settings.service.pipe.ValveRoomService;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;
import com.deyuanyun.pic.settings.util.HtmlToPdfUtil;
import com.itextpdf.text.DocumentException;
import jxl.read.biff.BiffException;
import org.apache.poi.ss.usermodel.Workbook;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/comm")
public class CommController extends AbstractBaseController {

    @Resource 
    private AttachmentService attachmentService;
	@Resource
	private PipeLineService pipeLineService;
	@Resource
	private PipeSegmentService pipeSegmentService;
	@Resource
	private ValveRoomService valveRoomService;
	@Resource
    private PipeLocationService pipeLocationService;
    

	/**
	 * 得到所有管道信息
	 */
	@ResponseBody
	@RequestMapping("/getLine.json")
	public void getLine()   {
		AjaxSupport.sendSuccessText("",pipeLineService.getLine());
	}

	/**
	 * 根据管道编号，得到所有管段信息
	 *
	 * @param lineId
     */
	@ResponseBody
	@RequestMapping("/getSegment.json")
	public void getSegment(String lineId)   {
		AjaxSupport.sendSuccessText("",pipeSegmentService.querySegmentListByLineId(lineId));
	}


	/**
	 * 根据管道编号获取管道信息
	 * @param pipeLineId
	 */
	@ResponseBody
    @RequestMapping("/queryPipeLineById.json")
    public void queryPipeLineById(@RequestParam(value="pipeLineId")String pipeLineId)   {
        
        PipePositionDTO pipePosition = pipeLocationService.queryPipeLinePosition(pipeLineId);
        
        AjaxSupport.sendSuccessText("",pipePosition);
    }
	/**
	 * 根据管段编号查询管段信息
	 * @param pipeSegmentId
	 */
	@ResponseBody
    @RequestMapping("/queryPipeSegmentById.json")
    public void queryPipeSegment(@RequestParam(value="pipeSegmentId")String pipeSegmentId)   {
        
	    PipePositionDTO pipePosition = pipeLocationService.queryPipeSegmentPosition(pipeSegmentId);
        
        AjaxSupport.sendSuccessText("",pipePosition);
    }
	
    /**
     * 根据管道编号，和管段名称
     * 
     * @param pipeLineId
     * @param pipeSegmentName
     */
    @ResponseBody
    @RequestMapping("/queryPipeSegment.json")
    public void queryPipeSegment(@RequestParam("pipeLineId") String pipeLineId
            ,@RequestParam(value="pipeSegmentName",required = false)String pipeSegmentName)   {
        
        List<PipeSegment> list = pipeSegmentService.queryPipeSegment(pipeLineId, pipeSegmentName);
        
        AjaxSupport.sendSuccessText("",list);
    }

    //根据管道编号、管段编号、桩或者阀室名称模糊查询桩或者阀室、最小绝对里程
    @ResponseBody
    @RequestMapping("/queryPipeSign.json")  
    public void queryPipeSign(@RequestParam("pipeLineId") String pipeLineId
            ,@RequestParam(value = "pipeSegmentId",required = false)String pipeSegmentId
            ,@RequestParam(value = "signName",required = false)String signName
            ,@RequestParam(value = "beginSignId",required = false)String beginSignId
            ,@RequestParam(value = "endSignId",required = false)String endSignId
            ,@RequestParam(value = "beginMileage",required = false)BigDecimal beginMileage
            ,@RequestParam(value = "endMileage",required = false)BigDecimal endMileage
            ,@RequestParam(value = "targetType",required = false)String targetType)   {
        //targetType=valveRoom，只查询场站，不查询阀室 
        //targetType=valveRoomStation，只查询场站阀室
        //targetType=valveRoomBall只查询有收发球筒的场站阀室
        
        //BigDecimal beginMileage = null;
        //BigDecimal endMileage = null;
        if(StringUtils.isNotEmpty(pipeSegmentId)){//客户端可能不提交管段编号
            PipePositionDTO pipePosition = pipeLocationService.queryPipeSegmentPosition(pipeSegmentId);
            if(StringUtils.isEmpty(beginSignId)){//如果未提交开始里程，就用管段的开始里程。
                beginMileage = pipePosition.getBeginMileage();
            }else{
                PipeLocationDTO beginSignPipeLocation = pipeLocationService.queryPipeLocationById(pipeLineId,beginSignId);
                beginMileage = beginSignPipeLocation.getMileage();
            }
            endMileage = pipePosition.getEndMileage();
        }
        if(StringUtils.isNotEmpty(endSignId)){//如果提交了终点位置，就用终点位置
            PipeLocationDTO beginSignPipeLocation = pipeLocationService.queryPipeLocationById(pipeLineId,endSignId);
            endMileage = beginSignPipeLocation.getMileage();
        }
        List<PipeLocationDTO> list = pipeLocationService.queryPipeLocation(pipeLineId, beginMileage, endMileage,signName,targetType);
        
        AjaxSupport.sendSuccessText("",list);
    }
    
	@ResponseBody
	@RequestMapping("/getValveRoom.json")
	public void getValveRoom(String lineId)   {
		AjaxSupport.sendSuccessText("",valveRoomService.queryValueRoomListByLineId(lineId));
	}

	@ResponseBody
	@RequestMapping("/getLineValveRoom.json")
	public void getLineValveRoom(String lineId, BigDecimal startMileage, BigDecimal endMileage)   {
		AjaxSupport.sendSuccessText("",valveRoomService.queryValueRoom(lineId, startMileage, endMileage));
	}

	@ResponseBody
    @RequestMapping("/getCode.json")
    public void getCode(@RequestParam("majorCode")String majorCode,@RequestParam("level")Short level)   {

	    //List<Code> codeList = BaseCodeUtils.getCodeList(majorCode);//getCodeList(majorCode,level);
	    List<Code> codeList = CodeUtil.getCodeList(majorCode,level);//getCodeList(majorCode,level);
	    
        AjaxSupport.sendSuccessText("success",codeList);
    }

    @ResponseBody
    @RequestMapping("/getCodeByParentId.json")
    public void getCodeByParentId(@RequestParam("majorCode")String majorCode,@RequestParam("parentId")String parentId)   {

        //List<Code> codeList = BaseCodeUtils.getCodeList(majorCode);//getCodeList(majorCode,level);
        List<Code> codeList = CodeUtil.getCodeListByParentId(majorCode, parentId);
        
        AjaxSupport.sendSuccessText("success",codeList);
    }
    @RequestMapping("/uploadProgress")
    public void uploadProgress(String clientId,
    		HttpServletRequest request,HttpServletResponse response)   {
    	response.setCharacterEncoding("UTF-8");
    	response.setContentType("text/text");
    	
    	try {
			response.getWriter().write(ExceplImportCheck.getProgress(clientId));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    
    /**
     * 等到字典信息
     *
     * @return
     */
	@ResponseBody
    @RequestMapping("/codes")
    public ModelAndView getCodes(String majorCode) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("result", CodeUtil.getCodeList(majorCode));
        return mv;
    }
    
    @RequestMapping("/upload")
    public void upload(@RequestParam MultipartFile file,
    		HttpServletRequest request,HttpServletResponse response)   {
    	
    	
    	Map param= RequestUtil.parseRequestParamToHashMap(request);
    	StringBuffer result=new StringBuffer("{\"status\":");
    	try{
    		param= UploadUtil.load(param,file);
    		attachmentService.updateInsert(param);
    		String url=param.get("url").toString();
        	String getRes=url;
        	result.append("0,").append("\"id\":").append("\"").append(param.get("id")).append("\"");
        	result.append(",\"url\":").append("\"").append(getRes).append("\",\"rootSrc\":\"").append(UploadUtil.SOURCE).append("\"}");
    	}catch(Exception e){
    		result.append("1,").append("\"err\":\"").append(e.getMessage()).append("\"}");
    	}
    	ResponseUtil.printl(response, result.toString(), "json");
    }
    
    /**
	  * excel 上传 检测demo
	  * @author 王敏
	  * @time 2015年11月12日下午3:31:05
	  * @param  file 参数列表
	  * @return   返回类型说明
	  * @see    
     */
    @RequestMapping("/excelUpload")
    public void excelUpload(@RequestParam MultipartFile file,
    		HttpServletRequest request,HttpServletResponse response)   {
    	String result="0";
    	ExceplImportCheck check=new ExceplImportCheck();
    	try {
    		check.addClient(request.getParameter("clientId"));
    		check.addDateCheck(2, "yyyyMMdd");
    		check.addRegCheck(3, "\\.*");
			check.execution(file, new CheckHandler(){
			
				@Override
				public String check(String val, int cel) {
					
					return null;
				}
				
			});
		} catch (Exception e) {
			e.printStackTrace();
			result="1";
		}
    	StringBuffer json=new StringBuffer("{\"status\":");
    	if(check.getLogSaveName() != null || result.equals("1")){
    		json.append(1).append(",\"log\":\"").append(request.getContextPath()).append(ExceplImportCheck.logSrcPath);
    		json.append(check.getLogSaveName()).append("\"}");
    	}else{
    		json.append(1).append("}");
    	}
    	ResponseUtil.printl(response, json.toString(), "json");
    	
    	
    	
    }

	/**
	 * 根据图片生成pdf
	 * @param name
	 * @throws IOException
	 * @throws DocumentException
     */
	@ResponseBody
	@RequestMapping("/downImgPdf.json")
	public void downImgPdf(String name
	        ,@RequestParam(value = "ydm",defaultValue = "true") Boolean ydm
	        ,HttpServletRequest request) throws IOException, DocumentException {
		String imgs[]=request.getParameterValues("imgs");
		StringBuffer html=new StringBuffer();
		ArrayList<String> pdfHtml=new ArrayList<String>();
		if(imgs != null)
		{
			for (String img:imgs)
			{
				html.append("<img src='").append(img).append("' />");
				System.out.println(html);
				html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
			}
		}
		HtmlToPdfUtil.build(html.toString(),name+ (ydm ? StringUtils.convertDateToString(new Date(),"yyyyMMdd") : ""));

	}

	/**
	 * 超时检查
	 * @param name
	 * @param request
	 * @throws IOException
	 * @throws DocumentException
     */
	@ResponseBody
	@RequestMapping("/checkOutTime.json")
	public void checkOutTime(String name,HttpServletRequest request) throws IOException, DocumentException {
		AjaxSupport.sendSuccessText("ok","ok");

	}

	/**
	 * 根据html 生成pdf
	 * @param htmls
	 * @param name
	 * @throws IOException
	 * @throws DocumentException
     */
	@ResponseBody
	@RequestMapping("/downHtmlPdf.json")
	public void downHtmlPdf(String htmls[],String name) throws IOException, DocumentException {

		if (htmls != null)
		{
			ArrayList<String> pdfHtml=new ArrayList<String>();
			for(String html:htmls)
			{
				pdfHtml.add(Jsoup.parse(html).toString());
			}
			HtmlToPdfUtil.build(pdfHtml,name+StringUtils.convertDateToString(new Date(),"yyyyMMdd"));
		}


	}
	/**
	 * 删除上传图片
	 * @param
	 * @return
	 * @throws
	 *
	 */
	@ResponseBody
	@RequestMapping("/deleteAttachment.json")
	public void  deleteAttachment(@RequestParam("attId") String attId){

		int delNum = attachmentService.deleteByPrimaryKey(attId);
		if(delNum > 0){
			AjaxSupport.sendSuccessText("","");
		}else{
			AjaxSupport.sendFailText("","");
		}
	}

    /**
     * 进入公共上传页面
     * @param modelMap
     * @return
     */
	@RequestMapping("/LeadingIn/upLoadPage.html")
	public ModelAndView upLoad(ModelMap modelMap){
		return new ModelAndView("/publicpage/uploadPage",modelMap);
	}

    /**
     * 根据图片生成pdf
     * @param name
     * @throws IOException
     * @throws DocumentException
     */
    @ResponseBody
    @RequestMapping("/downExcelTml.json")
    public void downExcelTml(@RequestParam("excelTmlPath")String excelTmlPath
            ,@RequestParam(value = "downFileName",defaultValue = "模板.xlsx") String downFileName
            ,HttpServletResponse response) throws IOException, DocumentException {
        String templateName="excl/" + excelTmlPath;
        try {
            Workbook workbook= ReadExcel.readExcelTemplate(templateName);
            Asserts.assertTrue(workbook != null, "没有找到模板。");
            WebUtil.setDownHeader(downFileName);
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.close();
        } catch (Exception e) {
            Asserts.assertTrue(false, "无法下载模板。");
        }
        
    }





	/**
	 * 下载导入excel时 的错误信息
	 * @param response
	 * @param html
	 * @throws Exception
	 */
	@RequestMapping(value="/LeadingIn/downExcelMessage.json")
	@ResponseBody
	public void downExcelMessage(HttpServletResponse response, String html){
		if (StringUtils.isEmpty(html)){
			response.setHeader("Content-Disposition","");
			AjaxResponse.sendText(response,"<script>alert('数据为空，不可进行下载操作!');</script>");
			return;
		}
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("message",html);

		OutputStream os = null;
		String realPath= PdfHelper.getPath();
		try {
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=dataErr.pdf" );
			os= PdfUtils.generateToServletOutputStream(realPath, "pdfFile/downErr.ftl", null, map, response);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			try {
				if(os != null){
					os.close();
				}
			} catch (IOException e) {
				logger.error(e);
			}
		}
	}
}
